package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.dto.request.house.HouseInfoUpdateRequest;
import cn.edu.ncu.housinghub.dto.request.house.HouseConditionRequest;
import cn.edu.ncu.housinghub.dto.request.house.HouseRequest;
import cn.edu.ncu.housinghub.dto.request.house.NearbyHouseRequest;
import cn.edu.ncu.housinghub.dto.request.house.PropertyVerificationRequest;
import cn.edu.ncu.housinghub.entity.house.ComplementaryFacilities;
import cn.edu.ncu.housinghub.dto.response.house.PageResult;
import cn.edu.ncu.housinghub.entity.house.House;
import cn.edu.ncu.housinghub.entity.house.PropertyVerification;
import cn.edu.ncu.housinghub.entity.user.Landlord;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.HouseMapper;
import cn.edu.ncu.housinghub.mapper.UserMapper;
import cn.edu.ncu.housinghub.service.HouseService;
import cn.edu.ncu.housinghub.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 提交房产认证（自动将普通用户转为房东）
     */
    @Transactional
    @Override
    public void submitPropertyVerification(PropertyVerificationRequest propertyVerificationRequest) {
        // 1. 检查用户角色，若为未实名用户，不让上传房源验证
        Long userId = propertyVerificationRequest.getUserId();
        User user = userService.findById(userId);
        if (!user.getIsIdentityVerified()) {
            throw new BusinessException(ErrorCodeConstant.USER_DONT_VERIFIED);
        }

        // 2. 检查房产认证是否已存在
        int count=findByPropertyNo(propertyVerificationRequest.getPropertyNo());
        if(count>0){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_EXIST);
        }

        // 2. 创建房产认证信息
        PropertyVerification verification = new PropertyVerification();
        verification.setUserId(userId);
        verification.setPropertyPicPath(propertyVerificationRequest.getPropertyPicPath());
        verification.setPropertyNo(propertyVerificationRequest.getPropertyNo());
        verification.setPropertyAddr(propertyVerificationRequest.getPropertyAddr());
        verification.setApplyTime(LocalDateTime.now());
        verification.setVerifyStatus(0); // 0=待审核
        verification.setIsDeleted(false);


        // 3. 插入认证信息到数据库
        houseMapper.insertPropertyVerification(verification);
    }

    /**
     * 审核通过后发布房源
     */
    @Transactional
    @Override
    public void publishHouseAfterVerification(HouseRequest houseRequest) {
        User user = userService.findById(houseRequest.getUserId());
        if (!user.getIsIdentityVerified()) {
            throw new BusinessException(ErrorCodeConstant.USER_DONT_VERIFIED);
        }

        if(!Objects.equals(user.getRole(), SystemConstant.ROLE_LANDLORD.getIntegerValue())){
            throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
        }

        //1. 验证房产信息是否已发布
        int count=findByPropertyVerifyId(houseRequest.getPropertyVerifyId());
        if(count>0){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_ALREADY_PUBLISHED);
        }

        PropertyVerification propertyVerification = houseMapper.selectPropertyVerificationById(houseRequest.getPropertyVerifyId());

        //2.查询认证信息 验证房产认证信息是否存在
        if(propertyVerification == null){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
        }

        if(propertyVerification.getVerifyStatus() != 1){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_PASSED);
        }



        //
        if(!Objects.equals(houseRequest.getUserId(), propertyVerification.getUserId())){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_OPERATION_NOT_AUTHORIZED);
        }

        Landlord landlord = userService.findLandlordByUserId(propertyVerification.getUserId());

        //2. 验证用户是否为房东
        if (landlord == null) {
            throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
        }


        //4. 构建房源信息
        House house = new House(houseRequest);
        Long complementaryFacilitiesId = null;
        ComplementaryFacilities complementaryFacilities=houseRequest.getComplementaryFacilities();
        //5. 添加配套设施信息,并获通过条件查询取配套设施ID
        if(complementaryFacilities != null){
            addComplementaryFacilities(complementaryFacilities);
            complementaryFacilitiesId = findComplementaryFacilitiesIdByCondition(complementaryFacilities);
        }
        house.setComplementaryFacilities(new ComplementaryFacilities(complementaryFacilitiesId));
        house.setLandlord(landlord);
        houseMapper.insertHouse(house);
    }

    /**
     * 根据propertyVerifyId查询认证信息
     */
    @Override
    public PropertyVerification findPropertyVerificationById(Long propertyVerifyId) {
        return houseMapper.selectPropertyVerificationById(propertyVerifyId);
    }

    @Override
    public List<House> selectAllHouses() {
        return houseMapper.selectAllHouses();
    }

    @Override
    public List<House> selectHousesByCondition(HouseConditionRequest condition) {
        return houseMapper.selectHousesByCondition(condition);
    }

    @Override
    public List<House> selectNearbyHouses(NearbyHouseRequest request) {
        return houseMapper.selectNearbyHouses(request);
    }

    @Override
    public PageResult<House> selectNearbyHousesWithPage(NearbyHouseRequest request) {
        // 获取总数
        Long total = houseMapper.countNearbyHouses(request);

        // 获取当前页数据
        List<House> houses = houseMapper.selectNearbyHouses(request);

        // 封装分页结果
        return new PageResult<>(houses, total, request.getPageNum(), request.getPageSize());
    }




    @Override
    public void addComplementaryFacilities(ComplementaryFacilities complementaryFacilities) {
        houseMapper.insertComplementaryFacilities(complementaryFacilities);
    }

    @Override
    public Long findComplementaryFacilitiesIdByCondition(ComplementaryFacilities condition) {
        return houseMapper.selectComplementaryFacilitiesIdByCondition(condition);
    }

    @Override
    public List<PropertyVerification> findPropertyVerificationByUserId(Long userId) {
        Landlord landlordByUserId = userService.findLandlordByUserId(userId);
        if (landlordByUserId==null) {
            //用户不是房东
            throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
        }
        return houseMapper.selectPropertyVerificationByUserId(userId);
    }

    @Override
    public List<House> findHouseByLandLordId(Long userId) {
        Landlord landlord = userMapper.selectLandlordByUserId(userId);
        if(landlord==null){
            throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
        }
        Long landlordId = landlord.getLandlordId();
        return houseMapper.selectHouseByLandLordId(landlordId);
    }

    @Override
    public int findByPropertyNo(String propertyNo) {
        return houseMapper.selectByPropertyNo(propertyNo);
    }

    @Override
    public int findByPropertyVerifyId(Long propertyVerifyId) {
        return houseMapper.selectByPropertyVerifyId(propertyVerifyId);
    }

    @Override
    public void modifyPropertyVerificationDeleted(Long propertyVerifyId,Long userId) {
        PropertyVerification propertyVerification = houseMapper.selectPropertyVerificationById(propertyVerifyId);
        if(propertyVerification==null){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
        }
        if(!userId.equals(propertyVerification.getUserId())){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_OPERATION_NOT_AUTHORIZED);
        }
        if(propertyVerification.getVerifyStatus() != 2 && propertyVerification.getVerifyStatus()!=3){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFY_STATUS_MISMATCH);
        }
        houseMapper.updatePropertyVerificationDeleted(propertyVerifyId);
    }

    @Override
    public void modifyBatchPropertyVerificationDeleted( List<Long> propertyVerifyIds, Long userId) {
        for (Long propertyVerifyId : propertyVerifyIds) {
            PropertyVerification propertyVerification = houseMapper.selectPropertyVerificationById(propertyVerifyId);
            if (propertyVerification == null) {
                throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
            }
            if (!userId.equals(propertyVerification.getUserId())) {
                throw new BusinessException(ErrorCodeConstant.PROPERTY_OPERATION_NOT_AUTHORIZED);
            }
            if (propertyVerification.getVerifyStatus() != 2 && propertyVerification.getVerifyStatus()!=3) {
                throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFY_STATUS_MISMATCH);
            }
        }
        houseMapper.updateBatchPropertyVerificationDeleted(propertyVerifyIds);
    }

    /**
     * 修改房源信息
     */
    @Override
    public void modifyHouseInfo(HouseInfoUpdateRequest infoUpdateRequest) {
        Long houseId = infoUpdateRequest.getHouseId();
        House house = houseMapper.selectHouseById(houseId);

        // 判断该房源是否存在
        if (house == null||house.getIsDeleted()) {
            throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_EXIST);
        }

        // 判断该房源是否处于未租状态，未租状态的房源才能修改信息
        if (house.getStatus()!=0){
            throw new BusinessException(ErrorCodeConstant.HOUSE_STATUS_MISMATCH);
        }

        Long userId = infoUpdateRequest.getUserId();
        Landlord landlord = userService.findLandlordByUserId(userId);

        // 判断房东信息是否存在
        if (landlord == null) {
            throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
        }
        // 验证房源是否属于当前操作的房东
        if(!landlord.getLandlordId().equals(house.getLandlord().getLandlordId())){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_OPERATION_NOT_AUTHORIZED);
        }

        House houseInfo = new House(infoUpdateRequest);
        houseMapper.updateHouseInfo(houseInfo);
    }

    @Override
    public void modifyComplementaryFacilities(Long houseId,ComplementaryFacilities complementaryFacilities) {
        House selectHouseById = houseMapper.selectHouseById(houseId);

        // 判断该房源是否存在
        if(selectHouseById==null||selectHouseById.getIsDeleted()){
            throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_EXIST);
        }

        ComplementaryFacilities complementaryFacilitiesInfo = selectHouseById.getComplementaryFacilities();

        // 判断该房源是否存在配套设施信息
        if(complementaryFacilitiesInfo==null){
            addComplementaryFacilities(complementaryFacilities);
            Long complementaryFacilitiesId =findComplementaryFacilitiesIdByCondition(complementaryFacilities);
            //如果配套设施信息插入失败，则返回错误
            if(complementaryFacilitiesId==null){
                throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR);
            }

            // 更新房源，将新插入的配套设施信息插入到房源中
            House house=new House();
            house.setHouseId(houseId);
            house.setComplementaryFacilities(new ComplementaryFacilities(complementaryFacilitiesId));
            houseMapper.updateHouseInfo(house);
        }

        // 验证房源是否处于未租状态，未租状态的房源才能修改信息
        if(selectHouseById.getStatus()!=0){
            throw new BusinessException(ErrorCodeConstant.HOUSE_STATUS_MISMATCH);
        }

        houseMapper.updateComplementaryFacilities(complementaryFacilities);
    }

    /**
     * 根据房产编号查询房产认证状态
     * @param propertyNo
     * @return
     */
    @Override
    public Integer findPropertyVerifyStatusByPropertyNo(String propertyNo) {
        Integer propertyVerifyStatus = houseMapper.selectPropertyVerifyStatusByPropertyNo(propertyNo);
        if(propertyVerifyStatus==null){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
        }
        return propertyVerifyStatus;
    }

    /**
     * 根据房产编号查询房产认证拒绝原因
     * @param propertyNo
     * @return
     */
    @Override
    public String findPropertyVerifyRefuseReasonByPropertyNo(String propertyNo) {
        if(houseMapper.selectPropertyVerifyStatusByPropertyNo(propertyNo)!=2){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFY_STATUS_MISMATCH);
        }
        String refuseReason = houseMapper.selectPropertyVerifyRefuseReasonByPropertyNo(propertyNo);
        if(refuseReason==null){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
        }
        return refuseReason;
    }

    /**
     * 根据房产编号取消房产认证
     * @param propertyNo
     */
    @Override
    public void modifyCancelPropertyVerifyByPropertyNo(String propertyNo) {
        Integer propertyVerifyStatus = houseMapper.selectPropertyVerifyStatusByPropertyNo(propertyNo);
        if(propertyVerifyStatus==null){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFICATION_NOT_EXIST);
        }
        if(propertyVerifyStatus!=0){
            throw new BusinessException(ErrorCodeConstant.PROPERTY_VERIFY_STATUS_MISMATCH);
        }
        houseMapper.updateCancelPropertyVerifyByPropertyNo(propertyNo);
    }

    /**
     *
     * @param houseId 房源id
     * @param houseStatus 房源状态 0=上架重新为待出租状态，2=下架
     */
    @Override
    public void modifyHouseStatus(Long houseId, Integer houseStatus) {
        House house = houseMapper.selectHouseById(houseId);
        if(house==null){
            throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_EXIST);
        }
        if(house.getStatus()!=2&&house.getStatus()!=0){
            throw new BusinessException(ErrorCodeConstant.HOUSE_STATUS_MISMATCH);
        }
        houseMapper.updateHouseStatus(houseId,houseStatus);
    }

    @Override
    public House findHouseByHouseId(Long houseId) {
        House house = houseMapper.selectHouseByHouseId(houseId);
        if (house==null){
            throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_EXIST);
        }
        ComplementaryFacilities complementaryFacilities = findComplementaryFacilitiesById(house.getComplementaryFacilities().getComplementaryFacilityId());

        house.setComplementaryFacilities(complementaryFacilities);
        return house;
    }

    @Override
    public ComplementaryFacilities findComplementaryFacilitiesById(Long id) {
        return houseMapper.selectComplementaryFacilitiesById(id);
    }

    @Override
    public House getHouseDetailById(Long houseId) {
        return houseMapper.selectHouseDetailById(houseId);
    }

}


